const { mysql } = require('../qcloud')
const config = require('../config')
const service = config.service

/**
 * 响应 GET 请求（返回用户记录信息）
 */
async function get(ctx, next) {
  const openId = ctx.query.open_id
  var res = await mysql('record').select('*').where('open_id', openId)
  console.log(res)
  if (res.length > 0) {
    ctx.state.data = res[0]
  } else {
    const newRecord = {
      open_id: openId,
      score: 0,
      gold: service.initGold
    }
    await mysql('record').insert(newRecord)
    ctx.state.data = newRecord
  }

}

/**
 * 添加用户记录信息
 */
async function post(ctx, next) {
  /**
   * 解析微信发送过来的请求体
   * 可查看微信文档：https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/receive.html#接收消息和事件
   */
  const body = ctx.request.body
  const res = await mysql('record').insert(body)
  ctx.state.data = res
}

/**
 * 添加用户记录信息
 */
async function put(ctx, next) {
  /**
   * 解析微信发送过来的请求体
   * 可查看微信文档：https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/receive.html#接收消息和事件
   */
  const record = ctx.request.body
  const res = await mysql('record').update(record).where('open_id', record.open_id)
  ctx.state.data = res
}

module.exports = {
  post,
  put,
  get
}
